package com.augrain.microframework.web;

import com.augrain.microframework.web.advice.ApiExceptionAdvice;
import com.augrain.microframework.web.advice.ApiExceptionHandlerResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * web自定义装配
 *
 * @author biaoy
 * @since 2020/11/25
 */
@Configuration
public class ApiAutoConfiguration implements WebMvcConfigurer {
    //
    // /**
    //  * 跨域支持配置
    //  */
    // @Override
    // public void addCorsMappings(CorsRegistry registry) {
    //     registry.addMapping("/**")
    //             .allowCredentials(true)
    //             .allowedOrigins("*")
    //             .allowedMethods("GET", "PUT", "DELETE", "POST", "OPTIONS")
    //             .maxAge(3600);
    // }

    // *******************自定义filter，完成相应的业务逻辑********************

    /**
     * 构建ApiContext对象，放入线程变量
     */
    @Bean
    public ApiParamRequestFilter apiParamsRequestFilter() {
        return new ApiParamRequestFilter();
    }

    @Bean("paramsFilter")
    public FilterRegistrationBean filterRegistrationBean(ApiParamRequestFilter apiParamsRequestFilter) {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setOrder(0);
        bean.setFilter(apiParamsRequestFilter);
        bean.addUrlPatterns("/*");
        return bean;
    }

    // *******************入参，返参统一处理开始*********************

    /**
     * 自定义响应结果处理
     */
    @Bean
    public ApiResponseAdvice apiResponseAdvice() {
        return new ApiResponseAdvice();
    }

    // *******************异常处理*********************
    /**
     * 全局异常处理
     */
    @Bean
    public ApiExceptionAdvice exceptionControllerAdvice() {
        return new ApiExceptionAdvice();
    }

    /**
     * 404异常处理
     */
    @Bean
    public ApiExceptionHandlerResolver apiExceptionHandlerResolver() {
        return new ApiExceptionHandlerResolver();
    }
}
